<?php
namespace app\home\controller;

use \app\common\controller\Homebase;
use \thans\Ret;
use \think\Db;
use \think\Loader;
use \think\Session;

class Posts extends Homebase
{
    public function _initialize()
    {
        $this->posts      = Loader::model('Posts');
        $this->options    = Loader::model('Options');
        $this->recycleBin = Loader::model('RecycleBin');
        $arr[0]['text']='模型列表';
        $arr[0]['url']='index';
        $arr[1]['text']='新增模型';
        $arr[1]['url']='addPage';
        $this->assign('third_menu', $arr);
    }

    /**
     *列表页面
     **/
    public function index()
    {
        $map['post_type'] = 'input_type';
        $list             = $this->posts->where($map)->paginate(10);
        $this->assign('list', $list);

        return $this->fetch();
    }

    /**
     *添加页面
     **/
    public function addPage()
    {
        if (input('id')) {
            $map['post_id'] = input('id');
            $list           = $this->posts->where($map)->find();
            if ($list) {
                $content = json_decode($list['post_content'], true);
                //根据输入的排序规则进行排序
                $arr      = inge_sortArrByField($content, 'sort_way');
                $det_data = json_decode($list['post_content'], true);
                $this->assign('list', $list);
                // $this->assign('data', json_encode($arr));
                $this->assign('data', $list['post_content']);
                $this->assign('attr_data', json_decode($list['post_remark'], true));
                $this->assign('det_data', $det_data);

            }
        } else {

        }
        $map2['option_name'] = 'input_type';
        $list                = $this->options->where($map2)->find();
        $this->assign('input_type', json_decode($list['option_value'], true));
        return $this->fetch('add');
    }

    /**
     *模型添加
     **/
    public function goAddModule()
    {
        $post_data['module_id']    = input('module_id/a');
        $post_data['module_name']  = input('module_name/a');
        $post_data['is_list']      = input('is_list/a');
        $post_data['is_request']   = input('is_request/a');
        $post_data['is_only_read'] = input('is_only_read/a');
        $post_data['input_way']    = input('input_way/a');
        $post_data['sort_way']     = input('sort_way/a');

        $post_data['check_rule']   = input('check_rule/a');
        $post_data['length']       = input('length/a');
        // var_dump($post_data);die();
        $post_data['search']       = input('search/a');
        $post_data['default_data'] = input('default_data/a');
        $len                       = count($post_data['module_id']);

        //高级属性数据 放在post_remark字段下
        $attr_data['front_script']  = input('front_script');
        $attr_data['front_edit']    = input('front_edit');
        $attr_data['behind_script'] = input('behind_script');
        $attr_data['behind_edit']   = input('behind_edit');
        $attr_data['post_engine']   = input('post_engine');
        $attr_data['post_mark']     = input('post_mark');
        $data['post_remark']        = json_encode($attr_data);
        Db::startTrans();
        try {
            for ($i = 0; $i < $len; $i++) {
                if (isset($post_data['is_list'][$i])) {
                    $post_data['is_list'][$i] = 1;
                } else {
                    $post_data['is_list'][$i] = 0;
                }

                if (isset($post_data['is_request'][$i])) {
                    $post_data['is_request'][$i] = 1;
                } else {
                    $post_data['is_request'][$i] = 0;
                }

                if (isset($post_data['is_only_read'][$i])) {
                    $post_data['is_only_read'][$i] = 1;
                } else {
                    $post_data['is_only_read'][$i] = 0;
                }
                $post_data2[$i]['module_id']    = $post_data['module_id'][$i];
                $post_data2[$i]['module_name']  = $post_data['module_name'][$i];
                $post_data2[$i]['is_list']      = $post_data['is_list'][$i];
                $post_data2[$i]['is_request']   = $post_data['is_request'][$i];
                $post_data2[$i]['is_only_read'] = $post_data['is_only_read'][$i];
                $post_data2[$i]['input_way']    = $post_data['input_way'][$i];
                $post_data2[$i]['sort_way']     = $post_data['sort_way'][$i];
                //每行的详细参数
                $post_data2[$i]['check_rule']   = $post_data['check_rule'][$i];
                $post_data2[$i]['length']       = $post_data['length'][$i];
                $post_data2[$i]['search']       = $post_data['search'][$i];
                $post_data2[$i]['default_data'] = $post_data['default_data'][$i];
                $post_data2[$i]['default_data'] = $post_data['default_data'][$i];
            }
            //对数组进行排序
            $post_data2 = inge_sortArrByField($post_data2, 'sort_way');


            $data['post_title'] = input('post_title');
            if ($data['post_title'] == '') {
                return $this->ret->setCode(1)->setMsg("名称不允许空")->toJson();
            }
            $data['post_type']    = "input_type";
            $data['post_author']  = session('u_id');
            $data['post_content'] = json_encode($post_data2);
            $data['post_status']  = 1;

            if (input('id')) {
                $map['post_id']           = input('id');
                $data['post_update_date'] = date("Y-m-d H:i:s", time());
                $data['post_update_ip']   = inge_get_ip();

                $res = $this->posts->where($map)->update($data);
                if ($res) {
                    Db::commit();
                    return $this->ret->setCode(1)->setMsg("修改成功")->setBack()->toJson();
                } else {
                    Db::rollback();
                    return $this->ret->setCode(1)->setMsg("修改失败")->toJson();
                }
            } else {
                $data['post_creater_date'] = date("Y-m-d H:i:s", time());
                $data['post_creater_ip']   = inge_get_ip();

                $id = $this->posts->insertGetId($data);
                if ($id) {
                    Db::commit();
                    return $this->ret->setCode(1)->setMsg("新增成功")->setBack()->toJson();
                } else {
                    Db::rollback();
                    return $this->ret->setCode(1)->setMsg("新增失败")->toJson();
                }
            }
        } catch (\Exception $e) {
            if (input('id')) {
                $msg['error'] = $e;
                Db::rollback();

                return $this->ret->setCode(1)->setMsg("修改失败")->toJson();
            } else {
                $msg['error'] = $e;
                Db::rollback();
                return $this->ret->setCode(1)->setMsg("新增失败")->toJson();
            }
        }
    }

    /**
     *模型删除
     *先根据id获取需要删除的数据,再进行删除,删除成功后将获取的数据插入回收站
     **/
    public function delModule()
    {
        $map['post_id'] = input('id');
        $posts          = $this->posts->where($map)->find();

        $result = $this->recycleBin->cutout(
            $this->posts,
            $posts,
            $map
        );

        if ($result) {
            return $this->ret->setCode(0)->setMsg("删除成功")->setReload()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg("删除成功")->setReload()->toJson();
        }
    }
    /**
     * 前端公用视图显示
     * @return [type] [description]
     */
    public function view($pid = 0, $pdid = 0)
    {
        $this->assign('third_menu', '');
        if ($pid) {
            $map['post_id'] = $pid;
            $list           = $this->posts->where($map)->find();
            if (!$list) {
                $this->error("参数错误");
            }
            $posts_data_id = $pdid;
            $list          = $list->toArray();
            $postData      = $this->posts->where('post_id', $posts_data_id)->find();
            $data          = isset($list['post_content']) ? $list['post_content'] : '';
            $data          = json_decode($data, true);
            $data          = is_array($data) ? $data : array();
            $postView      = new \thans\Common\Posts();
            $postView->init($data);
            //如果需要设置选择类型的默认数据 直接修改data的默认数据
            $postView->loadPostData(json_decode($postData['post_content'], true));
            $form   = $postView->getView();
            $script = $postView->getScriptAndStyle();
            $this->assign('posts', $list);
            $this->assign('script', $script);
            $this->assign('form', $form);
            $this->assign('post_id', input('pid'));
            $this->assign('posts_data_id', $posts_data_id);
            return $this->fetch();
        }
    }
    //公用数据提交
    public function add_edit($pid,$pdid=0)
    {
        $map['post_id'] = $pid;
        $post = $this->posts->where($map)->find();

        if(!$post){
            return $this->ret->setCode(1)->setMsg('模型不存在')->toJson();
        }
        if($pdid){
            $postData = $this->posts->where('posts_id',$pdid)->where('post_type',$pid)->find();
            if(!$postData){
                return $this->ret->setCode(1)->setMsg('模型数据不存在')->toJson();
            }
        }
        $post_content = isset($post['post_content']) ? $post['post_content'] : '';
        $post_content = json_decode($post_content,true);
        $post_content = is_array($post_content) ? $post_content : array();
        $postView = new \thans\Common\Posts();
        $postView->init($post_content);
        //$postView->init($data);
        // var_dump(input(''));
        $res=$postView->verfiy(input(''));
        if($res !== true){
                return $this->ret->setCode(1)->setMsg($res)->toJson();
        }
        $data['post_type']    = $pid;
        $data['post_title']   = $this->posts->getPostType($pid);
        $data['post_author']  = session('u_id');
        $data['post_content'] = json_encode(input('post.'));
        $data['post_is_del']  = 0;
        if ($pdid) {
            $map['post_id']           = $pdid;
            $map['post_type']         = $data['post_type'];
            $data['post_update_date'] = date("Y-m-d H:i:s", time());
            $data['post_update_ip']   = inge_get_ip();
            $res                      = $this->posts->where($map)->update($data);
            if ($res) {
                return $this->ret->setCode(0)->setMsg('更新成功')->toJson();
            } else {
                return $this->ret->setCode(1)->setMsg('更新失败')->toJson();
            }
        } else {
            $data['post_creater_date'] = date("Y-m-d H:i:s", time());
            $data['post_creater_ip']   = inge_get_ip();
            $id                        = $this->posts->insertGetId($data);
            if ($id) {
                return $this->ret->setCode(0)->setMsg('添加成功')->setReload()->toJson();
            } else {
                return $this->ret->setCode(1)->setMsg('添加失败')->toJson();
            }
        }
    }
    /**
     * 公共模型列表页面
     * @param $id 传入对应模型店id
     * @param $page 传入对应的列表页 默认为list
     * @return 视图路径
     */
    public function publicList($id, $page = 'list')
    {
        $map['post_id'] = $id;
        $list           = $this->posts->where($map)->find()->toArray();
        $this->assign('data', $list);
        $this->assign('mod_data', json_decode($list['post_content'], true));

        return $this->fetch('/posts/list/' . $page);
    }
    public function addOptions()
    {
        $arr = array(
            array(
                array(
                    'name' => '短文本框',
                    'id'   => 'short_test',
                ),
                array(
                    'name' => '长文本框',
                    'id'   => 'long_test',
                ),
                array(
                    'name' => '密码文本框',
                    'id'   => 'psw_test',
                ),
                array(
                    'name' => '高级文本框',
                    'id'   => 'ueditor',
                ),
                array(
                    'name' => '高级文本框-Mini',
                    'id'   => 'umeditor',
                ),
            ),
            array(
                array(
                    'name' => '选择时间',
                    'id'   => 'choose_time',
                ),
                array(
                    'name' => '选择具体时间',
                    'id'   => 'choose_details_time',
                ),
                array(
                    'name' => '选择日期',
                    'id'   => 'choose_date',
                ),
                array(
                    'name' => '数字',
                    'id'   => 'number',
                ),
                array(
                    'name' => '整数',
                    'id'   => 'int',
                ),
                array(
                    'name' => '金额',
                    'id'   => 'money',
                ),
                array(
                    'name' => '百分比',
                    'id'   => 'percent',
                ),
                array(
                    'name' => '邮箱',
                    'id'   => 'email',
                ),
            ),
            array(
                array(
                    'name' => '单选',
                    'id'   => 'radio',
                ),
                array(
                    'name' => '多选',
                    'id'   => 'checkbox',
                ),
                array(
                    'name' => '下拉菜单',
                    'id'   => 'select',
                ),
                array(
                    'name' => '下拉菜单(多选)',
                    'id'   => 'select_mul',
                ),
            ),
            array(
                array(
                    'name' => '填报人',
                    'id'   => 'people',
                ),
                array(
                    'name' => '文件上传',
                    'id'   => 'file',
                ),
                array(
                    'name' => '图片预览上传',
                    'id'   => 'image_file',
                ),
            ),
            array(
                array(
                    'name' => '随机数据',
                    'id'   => 'random_data',
                ),
                array(
                    'name' => '系统数据',
                    'id'   => 'sys_data',
                ),
            ),
        );
        $data['option_name']     = 'input_type';
        $data['option_value']    = json_encode($arr);
        $data['option_autoload'] = 1;
        echo '<pre>';
        print_r($arr);
        $id = Db::table('__OPTIONS__')->insertGetId($data);
        return $id;
    }
}
